﻿using System;
using System.Web;
using NHibernate;

namespace NH3SQLLogger
{
    /*
      Add this to app/web.config file .... to log sql's:
      <appSettings>
        <add key="nhibernate-logger" value="NH3SQLLogger.LoggerFactory, NH3SQLLogger" />
      </appSettings>      
     */
    public class LoggerFactory : ILoggerFactory
    {
        #region Fields (1)

        readonly string _fileName;

        #endregion Fields

        #region Constructors (2)

        public LoggerFactory()
        {
            var now = DateTime.Now.ToString("MM.dd.yyyy-hh-mm-ss");
            _fileName = string.Format("NH-SQL-Logs.{0}.html", now);
            //if IsInWeb
            if (HttpContext.Current != null)
                _fileName = HttpContext.Current.Server.MapPath(
                                string.Format("~/App_Data/{0}", _fileName)
                                );

            Syntaxhighlighter.Init(_fileName, "NH-SQL-Logs " + now);
        }

        ~LoggerFactory()
        {
            Syntaxhighlighter.End(_fileName);
        }

        #endregion Constructors

        #region Methods (2)

        // Public Methods (2) 

        public IInternalLogger LoggerFor(System.Type type)
        {
            if (type == null)
                return new NoLoggingInternalLogger();

            if (type != typeof(NHibernate.Tool.hbm2ddl.SchemaExport) && type != typeof(NHibernate.Tool.hbm2ddl.SchemaUpdate))
                return new NoLoggingInternalLogger();

            return new EventsLogger(_fileName);
        }

        public IInternalLogger LoggerFor(string keyName)
        {
            if (string.IsNullOrWhiteSpace(keyName))
                return new NoLoggingInternalLogger();

            if (keyName != "NHibernate.SQL")
                return new NoLoggingInternalLogger();

            return new EventsLogger(_fileName);
        }

        #endregion Methods
    }
}
